
package com.ifcar.app.view;

import com.ifcar.app.bean.PhotoInfo;
import com.ifcar.app.util.PicUtil;
import com.ifcar.app.util.Tools;
import com.ifcar.app.activity.R;


import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.preference.PreferenceManager;
import android.util.AttributeSet;
import android.view.View;
import android.widget.Toast;

import java.io.File;
import java.lang.ref.WeakReference;
import java.util.HashMap;
import java.util.List;

public class NewsImageViewer extends ImageViewer {

    private HashMap<String, LoadingImage> mLoadingImages = new HashMap<String, LoadingImage>();

    public NewsImageViewer(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public NewsImageViewer(Context context) {
        super(context);
    }

    @Override
    public void setList(List list, int position) {
        mLoadingImages.clear();
        getCurrentView().setTag(null);
        getNextView().setTag(null);
        super.setList(list, position);

    }

    @Override
    protected void setViewBitmap(ImageViewTouch view, Bitmap bitmap) {
        if (view == null) {
            return;
        }
        view.setImageBitmapResetBase(bitmap, true);
    }
    
    

    @Override
    protected boolean isCacheChanged(Object key, Bitmap cached) {
        return true;       
    }

    @Override
    protected Bitmap getBitmap(int position, Object key, Bitmap cached) {        
        final PhotoInfo info = (PhotoInfo) key;
        if (info == null) {
            if (cached != null) {
                cached.recycle();
            }
            return null;
        }
        
        LoadingImage loadingImage = mLoadingImages.get(info.getImgurl());
        if (loadingImage == null) {
            loadingImage = new LoadingImage(info);
            mLoadingImages.put(info.getImgurl(), loadingImage);
            if (cached != null) {
                cached.recycle();
                cached = null;
            }
        }
        
        if (cached == null || cached.isRecycled()) {            
            cached = loadingImage.getBitmap();            
        }

        View view = position == getCurrent() ? getCurrentView() : getNextView();
        loadingImage.setTag(view);
        view.setTag(loadingImage);

        View loadingBar = view.findViewById(R.id.loadingbar);

        if (cached == null) {
            loadingBar.setVisibility(View.VISIBLE);
        } else {
            loadingBar.setVisibility(View.GONE);
        }
        return cached;
    }

    private void callback(LoadingImage loadingImage, Object tag, Bitmap bitmap) {
        View view = (View) tag;
        if (view == null) {
            return;
        }
        if (view.getTag() != null && view.getTag().equals(loadingImage)) {
            View loadingBar = view.findViewById(R.id.loadingbar);
            loadingBar.setVisibility(View.GONE);
            ImageViewTouch imageViewTouch = (ImageViewTouch) view.findViewById(R.id.imageviewtouch);
            setViewBitmap(imageViewTouch, bitmap);
            if (bitmap == null) {
                Toast.makeText(getContext(), R.string.msg_loading_failed, Toast.LENGTH_SHORT)
                        .show();
            }
        }

        loadingImage.setTag(null);
    }

    private class LoadingImage {

        private PhotoInfo mPhotoInfo;

        private Context mContext;

        private WeakReference<Bitmap> mBitmap;

        private boolean mRunning;

        private Object mTag;

        public LoadingImage(PhotoInfo photoInfo) {
            mPhotoInfo = photoInfo;
            mContext = NewsImageViewer.this.getContext();
        }

        public void run() {
            
            SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(mContext);
            final Bitmap bitmap = Tools.isshowimg(sp.getBoolean("downpic", false), mContext) ? PicUtil.getBitMapForStringURL(
                    mPhotoInfo.getImgurl(), mContext) : null;

            NewsImageViewer.this.post(new Runnable() {
                @Override
                public void run() {
                    callback(bitmap);
                }
            });

            if (bitmap != null) {
                PicUtil.saveMyBitmap(PicUtil.phototempDir, mPhotoInfo.getPhotoid() + ".jpg", bitmap);
            }
        }

        private void callback(Bitmap bitmap) {
            if (bitmap != null) {
                mBitmap = new WeakReference<Bitmap>(bitmap);
            }

            NewsImageViewer.this.callback(this, mTag, bitmap);
            mRunning = false;
        }

        public void setTag(Object tag) {
            mTag = tag;
        }

        public Bitmap getBitmap() {
            Bitmap bitmap = null;

            // 取缓存
            if (mBitmap != null) {
                bitmap = mBitmap.get();
            }

            if (bitmap != null && !bitmap.isRecycled()) {
                return bitmap;
            }

            if (mRunning) {
                return null;
            }

            // 取本地文件
            if (mPhotoInfo == null) {
                return null;
            }

            String path = PicUtil.phototempDir + mPhotoInfo.getPhotoid() + ".jpg";
            File file = new File(path);
            if (file.exists()) {
                bitmap = PicUtil.fitSizeImg(path);
            }

            if (bitmap != null) {
                mBitmap = new WeakReference<Bitmap>(bitmap);
                return bitmap;
            }

            // 取网络文件
            mBitmap = null;
            
            if (Tools.CheckNetwork(mContext)) {
                mRunning = true;
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        LoadingImage.this.run();
                    }
                }).start();
            }
            return null;
        }
    }
}
